/*
 *    Copyright 2022 CManLH
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.lifeonwalden.ms.caller.ws;

import com.lifeonwalden.ms.caller.ws.bean.Parameter;
import com.lifeonwalden.ms.common.logger.LoggerUtil;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.FormattedMessage;

import javax.xml.namespace.QName;
import java.util.List;

public interface WsCaller {
    Logger logger = LoggerUtil.getLogger(WsCaller.class);

    static String call(String webServiceUrl, QName operationName, List<Parameter> parameterList) {
        Service service = new Service();
        Call call = null;
        try {
            call = (Call) service.createCall();
            call.setTargetEndpointAddress(webServiceUrl);
            call.setOperationName(operationName);

            Object[] request = new Object[0];
            if (null != parameterList && !parameterList.isEmpty()) {
                int size = parameterList.size();
                request = new Object[size];
                for (int i = 0; i < size; i++) {
                    Parameter param = parameterList.get(i);
                    call.addParameter(param.getName(), param.getXmlType(), param.getMode());
                    request[i] = param.getParameter();
                }
            }
            call.setReturnType(XMLType.XSD_STRING);

            return (String) call.invoke(request);
        } catch (Exception e) {
            logger.error(new FormattedMessage("Failed to call service {}", webServiceUrl), e);

            throw new RuntimeException(e);
        }
    }
}